<template>
  <div class="FcAmount">
    <fc-input-number v-bind="attrs" v-model="showValue"></fc-input-number>
    <fc-input type="textarea" :value="chineseAmount" disabled style="margin-top: 6px"></fc-input>
  </div>
</template>
<script setup name="FcAmount">
const attrs = useAttrs();
const emit = defineEmits(['update:modelValue'])
const props = defineProps({
  modelValue: {
    type: [String,
      Number],
    default: ''
  }
})
const showValue = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue',
        val)
  }
})
const chineseAmount = computed(() => {
  const number = parseFloat(showValue.value);
  if (isNaN(number)) return '';
  const unit = ['',
    '拾',
    '佰',
    '仟'];
  const bigUnit = ['',
    '万',
    '亿'];
  const digit = ['零',
    '壹',
    '贰',
    '叁',
    '肆',
    '伍',
    '陆',
    '柒',
    '捌',
    '玖'];
  const decimalUnit = ['角',
    '分'];
  let integerPart = Math.floor(number);
  let decimalPart = Math.round((number - integerPart) * 100);
  let integerStr = '';
  let decimalStr = '';
  // 处理整数部分
  if (integerPart === 0) {
    integerStr = '零';
  } else {
    let integerArr = integerPart.toString();
    let groupCount = Math.ceil(integerArr.length / 4);
    for (let i = 0; i < groupCount; i++) {
      let start = integerArr.length - (i + 1) * 4;
      let end = integerArr.length - i * 4;
      let group = integerArr.slice(start > 0 ? start : 0,
          end);
      let groupStr = '';
      for (let j = 0; j < group.length; j++) {
        let index = parseInt(group[j]);
        if (index === 0) {
          if (j < group.length - 1 && parseInt(group[j + 1]) !== 0) {
            groupStr += digit[index];
          }
        } else {
          groupStr += digit[index] + unit[group.length - j - 1];
        }
      }
      groupStr = groupStr.replace(/零+/g,
          '零')
          .replace(/零$/,
              '');
      if (groupStr) {
        integerStr = groupStr + bigUnit[i] + integerStr;
      }
    }
    integerStr = integerStr.replace(/零+/g,
        '零')
        .replace(/零([万亿])/g,
            '$1')
        .replace(/零$/,
            '');
  }
  // 处理小数部分
  if (decimalPart > 0) {
    let decimalArr = decimalPart.toString()
        .padStart(2,
            '0')
        .split('');
    for (let i = 0; i < decimalArr.length; i++) {
      let index = parseInt(decimalArr[i]);
      if (index !== 0) {
        decimalStr += digit[index] + decimalUnit[i];
      }
    }
  }
  let result = integerStr;
  if (decimalStr) {
    result += '元' + decimalStr;
  } else {
    result += '元整';
  }
  return result;
});
</script>
<style scoped lang="scss">
.FcAmount {
}
</style>
